package it.unibo.android.convoycruisecontrol.chiefboatsubsystem;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;


import it.unibo.convoycruisecontrol.chiefboatsubsystem.IFlagDisplay;
import it.unibo.convoycruisecontrol.chiefboatsubsystem.ObservableFlagDisplay;
import it.unibo.convoycruisecontrol.progettodesignandroid.R;
import it.unibo.convoycruisecontrol.progettodesignandroid.R.id;
import it.unibo.convoycruisecontrol.progettodesignandroid.R.layout;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;

public class FlagDisplayView extends LinearLayout implements Observer{

	private ObservableFlagDisplay flagDisplay = null;
	private List<TextView> labels;
	private Activity activity;

	public FlagDisplayView(Activity activity, ObservableFlagDisplay flagDisplay)
	{
		super(activity, null);

		this.activity = activity;

		this.labels = new ArrayList<TextView>();
		this.flagDisplay  = flagDisplay;
		flagDisplay.addObserver(this);
		initGui(activity);
	}

	private void initGui(Activity activity) {
		LayoutInflater layoutInflater = (LayoutInflater) activity
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		layoutInflater.inflate(R.layout.flagdisplay, this);

		int i = 0;
		LinearLayout linearLayout = (LinearLayout)findViewById(R.id.flagDisplay);
		for (Boolean flag : flagDisplay.getDisplayedFlags()) {
			TextView label = new TextView(activity);
			label.setText(createInformationsString(i,flag));
			label.setTextColor(android.graphics.Color.RED);
			labels.add(label);

			i++;

			//add to layout
			linearLayout.addView(label);
		}


	}

	private String createInformationsString(int n, Boolean bool)
	{
		StringBuilder builder = new StringBuilder();
		builder.append("Boat");
		builder.append(n);
		builder.append(": \t");
		builder.append(bool);

		return builder.toString();
	}

	@Override
	public void update(Observable arg0, Object arg1) {
		activity.runOnUiThread(new Runnable() {

			@Override
			public void run() 
			{
				int i = 0;
				for (TextView label : labels) {
					label.setText(createInformationsString(i,flagDisplay.getDisplayedFlags().get(i)));
					if(!(flagDisplay.getDisplayedFlags().get(i)))
						label.setTextColor(android.graphics.Color.RED);
					else
						label.setTextColor(android.graphics.Color.GREEN);
					i++;
				}	
			}
		});
	}
}
